package Offer;

/**
 * 矩阵中的路径
 * @author 是阿秋啊
 * @date 2022/04/13 10:19
 **/
public class Num12 {

    public boolean exist(char[][] board, String word) {
        char[] words = word.toCharArray();
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (helper(board, words, i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean helper(char[][] board, char[] words, int i, int j, int k) {
        if (i >= board.length || j >= board[0].length || i < 0 || j < 0 || board[i][j] != words[k]) {
            // 数组越界，字符不符合
            return false;
        }
        if (k == words.length - 1) {
            return true;
        }
        board[i][j] = '\0';
        boolean ret = helper(board, words, i + 1, j, k + 1) || helper(board, words, i - 1, j, k + 1)
                || helper(board, words, i, j + 1, k + 1) || helper(board, words, i, j - 1, k + 1);
        // 递归搜索匹配字符串过程中，需要 board[i][j] = '/' 来防止 ”走回头路“ 。当匹配字符串不成功时，会回溯返回，
        // 此时需要board[i][j] = tmp 来”取消对此单元格的标记”。 在DFS过程中，每个单元格会多次被访问的，
        // board[i][j] = '/'只是要保证在当前匹配方案中不要走回头路。
        board[i][j] = words[k];
        return ret;
    }
}
